import { Context, Next } from 'koa'
import permissionService from '@/service/permission.service'
import { IPermissionTypes } from '@/types/permission.types'
import {
  PARAMS_IS_REQUIRED,
  PERMISSION_ALREADY_EXISTS,
  PID_NOT_EXISTS,
  ID_PARAMS_IS_REQUIRED
} from '@/constants/error-types'

/**
 * 新增权限校验
 * @param ctx
 * @param next
 * @returns
 */
const verifyPermission = async (ctx: Context, next: Next) => {
  // 获取请求路径
  const method = ctx.request.method

  // 获取参数
  const {
    id,
    name,
    type,
    pid
  } = ctx.request.body as unknown as IPermissionTypes

  // 参数校验
  if (!name || !type) {
    const error = new Error(PARAMS_IS_REQUIRED)
    return ctx.app.emit('error', ctx, error)
  }
  // 如果是修改菜单，必须携带id
  if (method === 'put' && !id) {
    const error = new Error(ID_PARAMS_IS_REQUIRED)
    return ctx.app.emit('error', ctx, error)
  }
  // 权限名称校验
  const perRes: any = await permissionService.getPermissionByName(name, id || -1)
  const permission = perRes[0]
  if (permission.length) {
    const error = new Error(PERMISSION_ALREADY_EXISTS)
    return ctx.app.emit('error', ctx, error)
  }
  // 父权限id校验, 顶级菜单不校验
  if (pid) {
    const perRes: any = await permissionService.getPermissionById(pid)
    const permission = perRes[0]
    if (!permission.length) {
      const error = new Error(PID_NOT_EXISTS)
      return ctx.app.emit('error', ctx, error)
    }
  }
  await next()
}

export {
  verifyPermission
}